//
//  ImageDownloader.m
//  FrameTest
//
//  Created by Tiger on 11-11-2.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ImageDownloader.h"


@implementation ImageDownloader
@synthesize delegate;

- (id)initWithUrl:(NSString *)strUrl indexPath:(NSIndexPath *)index
{
	self = [super init];
	if (self) {
		imageUrl = [[NSString alloc]initWithString:strUrl];
		indexPath = [index retain];
		imageData = [[NSMutableData alloc]init];
	}
	return self;
}

- (id)initWithUrl:(NSString *)strUrl index:(NSInteger)index
{
	self = [super init];
	if (self) {
		imageUrl = [[NSString alloc]initWithString:strUrl];
		_index = index;
		imageData = [[NSMutableData alloc]init];
	}
	return self;
}

- (void)dealloc {
	[imageUrl release];
	[indexPath release];
	[imageData release];
    [super dealloc];
}

- (void)cancel {
	delegate = nil;
	[imageData release];
	imageData = nil;
	conn = nil;
}

- (UIImage *)getImage {
	UIImage *image = [ImageCache selectImageWithUrl:imageUrl];
	
	if (image) {
		return image;
	}
	else {
		NSURL *url = [NSURL URLWithString:imageUrl];
		conn = [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url] delegate:self];
		return nil;
	}
}

#pragma mark -
#pragma mark Download support (NSURLConnectionDelegate)
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	[imageData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [imageData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	delegate = nil;
	[imageData release];
	imageData = nil;
	conn = nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	if ([imageData length]>0) {
		[ImageCache cacheImageData:imageData strUrl:imageUrl];
		
		if ([delegate respondsToSelector:@selector(imageDidFinishLoad:indexPath:)]) {
			UIImage *image = [UIImage imageWithData:imageData];
			[delegate imageDidFinishLoad:image indexPath:indexPath];
		}
        
        if ([delegate respondsToSelector:@selector(imageDidFinishLoad:index:)]) {
			UIImage *image = [UIImage imageWithData:imageData];
			[delegate imageDidFinishLoad:image index:_index];
		}
	}
	
	delegate = nil;
	[imageData release];
	imageData = nil;
	conn = nil;
}

@end
